using System;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;

namespace Azure.Infrastructure
{
    public abstract class FeedResult : ActionResult
    {
        private readonly SyndicationFeed _feed;

        protected FeedResult(SyndicationFeed feed)
        {
            _feed = feed;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = ContentType;
            SyndicationFeedFormatter formatter = CreateFormatter(_feed);

            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                formatter.WriteTo(writer);
            }
        }

        public SyndicationFeed Feed
        {
            get
            {
                return _feed;
            }
        }

        protected abstract SyndicationFeedFormatter CreateFormatter(SyndicationFeed feed);

        protected abstract string ContentType { get; }
    }

    public class AtomFeedResult : FeedResult
    {
        public AtomFeedResult(SyndicationFeed feed)
            : base(feed)
        {
        }

        protected override SyndicationFeedFormatter CreateFormatter(SyndicationFeed feed)
        {
            return feed.GetAtom10Formatter();
        }

        protected override string ContentType
        {
            get { return "application/atom+xml"; }
        }
    }
}